﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IRCBot.Messages
{
    public class IncomingMessage
    {
        public string Sender { get; set; }
        public string MessageType { get; set; }
        public string Channel { get; set; }
        public string Command { get; set; }
        public string Parameters { get; set; }

        public IncomingMessage(string messageData)
        {
            try
            {
                Sender = "";
                MessageType = "";
                Channel = "";
                Command = "";
                Parameters = "";

                string[] ex = messageData.Split(new char[] { ' ' }, 5);

                if (ex[0] == "PING")
                {
                    Command = "PING";
                    Parameters = ex[1];
                }
                else if (ex.Count() > 3)
                {
                    Sender = ex[0];
                    MessageType = ex[1];
                    Channel = ex[2];
                    Command = ex[3];
                    if (ex.Count() > 4)
                        Parameters = ex[4];
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing message: " + messageData + ". " + ex.Message);
            }
        }

        public string GetParameterNumber(int index)
        {
            string[] parameters = Parameters.Split(' ');
            if (parameters.Count() >= index)
                return parameters[index];
            
            return "";
        }

        public string GetParametersFromIndex(int index)
        {
            string result = "";
            string[] parameters = Parameters.Split(' ');
            if (parameters.Count() >= index)
                for (int i = index; i < parameters.Count(); i++)
                {
                    if (result != "")
                        result += " ";
                    result += parameters[i];
                }

            return result;
        }

        public string ToString()
        {
            return Sender + " --- " + MessageType + " --- " + Channel + " --- " + Command + " --- " + Parameters;
        }
    }
}
